package pres.lnk.utils;

import java.util.Objects;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;

/**
 * <p>获取值时空指定处理工具</p>
 * <a href="https://blog.csdn.net/lnkToKing/article/details/84031983">使用说明</a>
 *
 * @Author lnk
 * @Date 2018/11/13
 */
public class NullPointUtil {

    public static <T> T get(Supplier<T> operator, T defaultValue) {
        try {
            T result = operator.get();
            return Objects.requireNonNull(result);
        } catch (NullPointerException ignore) {
            return defaultValue;
        }
    }

    public static <T> T get(Supplier<T> operator) {
        return get(operator, null);
    }

    public static <T> Optional<T> getOptional(Supplier<T> operator) {
        return Optional.ofNullable(get(operator));
    }

    public static boolean test(BooleanSupplier operator) {
        try {
            return operator.getAsBoolean();
        } catch (NullPointerException ignore) {
            return false;
        }
    }

    public static boolean testOrNull(BooleanSupplier operator) {
        try {
            return operator.getAsBoolean();
        } catch (NullPointerException ignore) {
            return true;
        }
    }

    public static boolean isNull(Supplier<?> operator) {
        try {
            Object result = operator.get();
            return Objects.isNull(result);
        } catch (NullPointerException ignore) {
            return true;
        }
    }

    public static boolean nonNull(Supplier<?> operator) {
        return !isNull(operator);
    }

    public static boolean equals(Supplier<?> operator1, Supplier<?> operator2) {
        return getOptional(operator1).equals(getOptional(operator2));
    }
}
